﻿using System;
using System.Threading.Tasks;
using IdentityServer4.Services;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.Account.Public.Web.Pages.Account;
using Volo.Abp.DependencyInjection;

namespace Volo.Abp.Account.Web.Pages.Account
{
	[ExposeServices(
		typeof(LogoutModel)
	)]
	public class IdentityServerSupportedLogoutModel : LogoutModel
	{
		protected IIdentityServerInteractionService Interaction { get; }

		public IdentityServerSupportedLogoutModel(IIdentityServerInteractionService interaction)
		{
			this.Interaction = interaction;
		}

		public override async Task<IActionResult> OnGetAsync()
		{
			await base.SignInManager.SignOutAsync();
			string text = base.Request.Query["logoutId"].ToString();
			if (!string.IsNullOrEmpty(text))
			{
				var logoutRequest = await this.Interaction.GetLogoutContextAsync(text);
				string postLogoutRedirectUri = logoutRequest.PostLogoutRedirectUri;
				if (!string.IsNullOrEmpty(postLogoutRedirectUri))
				{
					return base.Redirect(postLogoutRedirectUri);
				}
			}
			IActionResult result;
			if (base.ReturnUrl != null)
			{
				result = this.LocalRedirect(base.ReturnUrl);
			}
			else
			{
				result = this.RedirectToPage("/Account/Login");
			}
			return result;
		}
	}
}
